<?php
function PWD_debug($PWD, $suf, $str) {
	global $debug_echoPWD;
	if ($debug_echoPWD && is_dir ( $PWD ) && is_readable ( $PWD ) && ($suf != "logs" || is_writable ( $PWD ))) {
		print $str;
		$debug_echoPWD = 0;
	}
}
function PWD_check($PWD, $suf) {
	// debug ("&#160; &#160; <b>PWD = </b>$PWD; <b>suf = </b>$suf;<br/>&#160; &#160; &#160; is_dir? <b style='color:green'>" . is_dir($PWD) . "</b>; is_readable? <b style='color:green'>" . is_readable($PWD) . "</b>; is_writable? <b style='color:green'>" . is_writable($PWD) . "</b><br/>", 2);
	return (! is_dir ( $PWD ) || ! is_readable ( $PWD ) || ($suf == "logs" && ! is_writable ( $PWD )));
}
function debug($str, $level = 0) {
	global $debug;
	
	if ($debug > $level) {
		print "<div class=\"debug\">$str</div>\n";
	}
}
function getPWD($suf = "", $doDynCheck = true, $debug_echoPWD = 1) // set 0 to hide (for security purposes!)
{
	global $App;
	$PR = "gef";
	debug ( "<br/><b>PR = </b>$PR, <b>suf = </b>$suf</br>", 2 );
	$PWDs = array ();
	
	if ($doDynCheck) {
		// dynamic assignments
		$PWD = $App->getDownloadBasePath () . "/$PR/" . $suf;
		$PWDs [] = $PWD;
		PWD_debug ( $PWD, $suf, "<!-- Found[1gDBP] $PWD -->" );
		
		// second dynamic assignment
		if (PWD_check ( $PWD, $suf )) {
			$PWD = $_SERVER ["DOCUMENT_ROOT"] . "/$PR/" . $suf;
			$PWDs [] = $PWD;
			PWD_debug ( $PWD, $suf, "<!-- Found[1DR+PR] $PWD -->" );
		}
		
		if (! PWD_check ( $PWD, $suf )) {
			debug ( "'$suf' ended up with '$PWD' (is_readable: <b style='color:green'>" . is_readable ( $PWD ) . "</b>, is_dir: <b style='color:green'>" . is_dir ( $PWD ) . "</b>)" );
			return $PWD;
		}
	}
	$PWD = "";
	
	// static assignments
	if (PWD_check ( $PWD, $suf )) {
		$servers = array (
				"/buildbox(?:\.torolab\.ibm\.com)?/" => "/home/www-data/build",
				"/build\.eclipse\.org/" => "/opt/public/modeling/build",
				"/localhost/" => "/home/www-data/build",
				"/download1\.eclipse\.org/" => "/home/local/data/httpd/download.eclipse.org" 
		);
		
		foreach ( array_keys ( $servers ) as $z ) {
			$PWD = $servers [$z] . "/$PR/$suf";
			if (preg_match ( $z, $_SERVER ["HTTP_HOST"] ) && ! PWD_check ( $PWD, $suf )) {
				$PWDs [] = $PWD;
				PWD_debug ( $PWD, $suf, "<!-- Found[3stat] -->" );
			}
		}
		foreach ( array_keys ( $servers ) as $z ) {
			$PWD = $servers [$z] . "/$suf";
			if (preg_match ( $z, $_SERVER ["HTTP_HOST"] ) && ! PWD_check ( $PWD, $suf )) {
				$PWDs [] = $PWD;
				PWD_debug ( $PWD, $suf, "<!-- Found[3stat2] -->" );
			}
		}
	}
	$PWD = "";
	
	// try a default guess: /home/www, two options
	if (PWD_check ( $PWD, $suf )) {
		$data = array (
				4 => array (
						"checkdir" => "/home/data/httpd/download.eclipse.org/",
						"tries" => array (
								"/home/data/httpd/download.eclipse.org/$suf",
								"/home/data/httpd/download.eclipse.org/$PR/$suf",
								"/home/data/httpd/download.eclipse.org/tools/$suf",
								"/home/data/httpd/download.eclipse.org/tools/$PR/$suf",
						) 
				),
				5 => array (
						"checkdir" => "/home/data2/httpd/download.eclipse.org/",
						"tries" => array (
								"/home/data2/httpd/download.eclipse.org/$suf",
								"/home/data2/httpd/download.eclipse.org/$PR/$suf",
								"/home/data2/httpd/download.eclipse.org/tools/$suf",
								"/home/data2/httpd/download.eclipse.org/tools/$PR/$suf",
						) 
				)
		);
		
		foreach ( array_keys ( $data ) as $y ) {
			$PWD = $data [$y] ["checkdir"];
			if (is_dir ( $PWD ) && is_readable ( $PWD )) {
				foreach ( array_keys ( $data [$y] ["tries"] ) as $z ) {
					// debug("&#160; &#160; &#160; &#160; &#160; \$data[$y][\"tries\"][$z] = " . $data[$y]["tries"][$z],3);
					$PWD = $data [$y] ["tries"] [$z];
					if ($PWD && ! PWD_check ( $PWD, $suf )) {
						PWD_debug ( $PWD, $suf, "<!-- Found: defaults[${y}][$z] -->" );
						$PWDs [] = $PWD;
						break 2;
					}
				}
			}
		}
	}
	$PWD = "";
	
	krsort ( $PWDs );
	reset ( $PWDs );
	// debug_r($PWDs, "<hr>PWDs: ", "<hr>", 2);
	foreach ( $PWDs as $i => $PWD ) {
		debug ( " &#160; &#160; $i : $PWD", 9 );
		if (! PWD_check ( $PWD, $suf )) {
			debug ( "'$suf' ended up with '$PWD' (is_readable: <b style='color:green'>" . is_readable ( $PWD ) . "</b>, is_dir: <b style='color:green'>" . is_dir ( $PWD ) . "</b>)" );
			return $PWD;
		}
	}
	
	debug ( "<!-- PWD not found! -->" );
	debug ( "'$suf' ended up with '$PWD' (is_readable: <b style='color:green'>" . is_readable ( $PWD ) . "</b>, is_dir: <b style='color:green'>" . is_dir ( $PWD ) . "</b>)" );
	return $PWD;
}
function loadDirSimple($dir, $ext, $type) // 1D array, not 2D
{
	$stuff = array ();
	
	if (is_dir ( $dir ) && is_readable ( $dir )) {
		$handle = opendir ( $dir );
		while ( ($file = readdir ( $handle )) !== false ) {
			if (preg_match ( "/$ext$/", $file ) && ! preg_match ( "/^\.{1,2}$/", $file )) {
				if (($type == "d" && is_dir ( "$dir/$file" )) || ($type == "f" && is_file ( "$dir/$file" ))) {
					$stuff [] = $file;
				}
			}
		}
		closedir ( $handle );
	} else {
		global $hadLoadDirSimpleError;
		if (! $hadLoadDirSimpleError) {
			$issue = (! is_dir ( $dir ) ? "NOT FOUND" : (! is_readable ( $dir ) ? "NOT READABLE" : "PROBLEM"));
			print "<p>Directory ($dir) <b>$issue</b> on mirror: <b>" . $_SERVER ["HTTP_HOST"] . "</b>!</p>";
			print "<p>Please report this error to <a href=\"mailto:webmaster@eclipse.org?Subject=Directory ($dir) $issue in scripts.php::loadDirSimple() on mirror " . $_SERVER ["HTTP_HOST"] . "\">webmaster@eclipse.org</a>, or make directory readable.</p>";
			$hadLoadDirSimpleError = 1;
		}
	}
	
	return $stuff;
}
function getDownloadScript() {
	global $PR;
	// if this is a GEF page, use /gef/download.php
	$dlScriptFile = $_SERVER ["DOCUMENT_ROOT"] . "/" . $PR . "/download.php";
	if (is_file ( $dlScriptFile )) {
		$downloadScript = "http://www.eclipse.org/" . $PR . "/download.php?file=";
	} else {
		$downloadScript = "http://www.eclipse.org/downloads/download.php?file=";
	}
	return $downloadScript;
}
function getBuildsFromDirs($PWD) // massage the builds into more useful structures
{
	$branchDirs = loadDirSimple ( $PWD, ".*", "d" );
	$buildDirs = array ();
	
	foreach ( $branchDirs as $branch ) {
		$buildDirs [$branch] = loadDirSimple ( "$PWD/$branch", "[IRS]\d{12}", "d" );
	}
	
	$builds_temp = array ();
	foreach ( $buildDirs as $br => $dirList ) {
		foreach ( $dirList as $dir ) {
			$ty = substr ( $dir, 0, 1 ); // first char is build type
			$builds_temp [$br] [$ty] [] = $dir;
		}
		uksort ( $builds_temp [$br], "compareBuilds" );
	}
	
	return $builds_temp;
}
function getBuildTypes($branches, $buildtypes) {
	$arr = array ();
	
	foreach ( $branches as $branch ) {
		$sortedKeys = array_keys ( $buildtypes );
		usort ( $sortedKeys, "compareBuilds" );
		foreach ( $sortedKeys as $z ) {
			if (! array_key_exists ( $branch, $arr )) {
				$arr [$branch] = array ();
			}
			
			// [2.0][N]
			$arr [$branch] [$z] = "$branch {$buildtypes[$z]} Build";
		}
	}
	
	return $arr;
}
function compareBuilds($b1, $b2) {
	$a;
	$b;
	// compare builds to sort them in order R S I M N
	switch ($b1) {
		case 'R' :
			$a = 4;
			break;
		case 'S' :
			$a = 3;
			break;
		case 'I' :
			$a = 2;
			break;
		case 'M' :
			$a = 1;
			break;
		default :
			$a = 0;
			break;
	}
	switch ($b2) {
		case 'R' :
			$b = 4;
			break;
		case 'S' :
			$b = 3;
			break;
		case 'I' :
			$b = 2;
			break;
		case 'M' :
			$b = 1;
			break;
		default :
			$b = 0;
			break;
	}
	if($a == $b) {
		// sort lexigraphically (in case build type is identical)
		return strcmp($b1, $b2);
	}
	return $b - $a;
}
function IDtoDateStamp($ID, $style) // given N200402121441, return date("D, j M Y -- H:i (O)")
{
	$styles = array (
			'Y/m/d H:i',
			"D, j M Y -- H:i (O)",
			'Y/m/d' 
	);
	$m = null;
	if (preg_match ( "/(\d{4})(\d\d)(\d\d)(?:_)?(\d\d)(\d\d)/", $ID, $m )) {
		$ts = mktime ( $m [4], $m [5], 0, $m [2], $m [3], $m [1] );
		return date ( $styles [$style], $ts );
	}
	
	return "";
}
function createFileLinks($PR, $PWD, $branch, $ID, $dls, $filePre, $ziplabel = "") // the new way - use a ziplabel pregen'd from a dir list!
{
	global $suf, $extraZips;
	$uu = 0;
	
	if (! $ziplabel) {
		$zips_in_folder = loadDirSimple ( "$PWD/$branch/$ID/", "(\.zip|\.tar\.gz)", "f" );
		$ziplabel = preg_replace ( "/(.+)\-([^\-]+)(\.zip|\.tar\.gz)/", "$2", $zips_in_folder [0] ); // grab first entry
	}
	
	$cnt = - 1; // for use with static prefix list
	
	$echo_out_all = "";
	
	foreach ( array_keys ( $dls) as $z ) {
		$echo_out = "";
		foreach ( $dls [$z] as $label => $u ) {
			$cnt ++;
			if (! is_array ( $u )) // for compatibilty with uml2, where there's no "RT" value in $u
{
				$u = $u ? array (
						"-$u" 
				) : array (
						"" 
				);
			}
			
			$tries = array ();
			foreach ( $u as $ux ) {
				$tries [] = "$branch/$ID/$filePre$ux-$ziplabel.zip"; 
				$tries [] = "$branch/$ID/$filePre$ux-$ziplabel.tar.gz";
			}
			$outNotFound = "<i>$filePre";
			if (sizeof ( $u ) > 1) {
				$outNotFound .= "</i>{";
				foreach ( $u as $ui => $ux ) {
					$outNotFound .= ($ui > 0 ? "," : "") . $ux;
				}
				$outNotFound .= "}<i>";
			} else {
				$outNotFound .= $u [0];
			}
			$outNotFound .= "-$ziplabel ...</i>";
			$out = "";
			foreach ( $tries as $y ) {
				if (is_file ( "$PWD/$y" )) {
					$out = fileFound ($PR, "$PWD/", $y, $label );
					break;
				}
			}
			if ($out) {
				$echo_out .= "<li class=\"separator\">\n";
				$echo_out .= $out;
				$echo_out .= "</li>\n";
			} else if (! isset ( $extraZips ) || ! is_array ( $extraZips ) || ! in_array ( $filePre . $u [0], $extraZips )) // $extraZips defined in downloads/index.php if necessary
{
				$echo_out .= "<li>\n";
				$echo_out .= $outNotFound;
				$echo_out .= "</li>\n";
			}
			$uu ++;
		}
		if ($echo_out) // if the whole category is empty, don't show it (eg., GEF)
{
			$echo_out_all .= "<li><img src=\"/modeling/images/dl.gif\" alt=\"Download\"/> $z\n<ul>\n" . $echo_out . "</ul>\n</li>\n";
		}
	}
	
	return $echo_out_all;
}
function fileFound($PR, $PWD, $url, $label, $md5AlignRight = true, $icon = null) {
	global $downloadScript;
	
	$out = "";
	$mid = "/tools/gef/downloads/drops/$PR/"; // new for www.eclipse.org centralized download.php script
	$md5files = array (
			"$url.md5",
			preg_replace ( "#/([^/]+$)#", "/checksum/$1", $url ) . ".md5" 
	);
	foreach ( $md5files as $md5file ) {
		if (is_file ( $PWD . $md5file )) {
			$out .= "<span style=\"float:right;\">" . pretty_size ( filesize ( "$PWD$url" ) ) . " (<a href=\"" . "http://download.eclipse.org" . "$mid$md5file\">md5</a>)</span>";
			break;
		}
	}
	// return $md5AlignRight ? $out . "<a href=\"$downloadScript$mid$url\">$label</a>" :
	// "<a href=\"$downloadScript$mid$url\">$icon</a>&nbsp;<a href=\"$downloadScript$mid$url\">$label</a>" . $out;
	return "<a href=\"$downloadScript$mid$url\">$icon</a><a href=\"$downloadScript$mid$url\">$label</a>" . $out;
}
function pretty_size($bytes) {
	$sufs = array (
			"B",
			"K",
			"M",
			"G",
			"T",
			"P" 
	); // we shouldn't be larger than 999.9 petabytes any time soon, hopefully
	$suf = 0;
	
	while ( $bytes >= 1000 ) {
		$bytes /= 1024;
		$suf ++;
	}
	
	return sprintf ( "%3.1f%s", $bytes, $sufs [$suf] );
}
function showBuilds($PR, $PWD, $branch, $IDs, $label, $filePre, $dls, &$c) {
	global $showAll, $showMax;
	$i = 0;
	foreach ( $IDs as $ID ) {
		// output builds for branch and type, 3.10.0 -> R ->
		print outputBuild ($PR, $PWD, $branch, $ID, $label, $filePre, $dls, $c ++ );
		$i ++;
		
		if (! $showAll && $i == $showMax && $i < sizeof ( $IDs )) {
			print showToggle ( $showAll, $showMax, sizeof ( $IDs ) );
			break;
		} else if ($showAll && sizeof ( $IDs ) > $showMax && $i == sizeof ( $IDs )) {
			print showToggle ( $showAll, $showMax, sizeof ( $IDs ) );
		}
	}
}
function outputBuild($PR, $PWD, $branch, $ID, $label, $filePre, $dls, $c) {
	global $hiddenBuilds;
	
	foreach ( $hiddenBuilds as $hb ) {
		if (trim ( $hb ) == "$PR/$branch/$ID") {
			debug ( "Build $PR/$branch/$ID is hidden, pending mirror replication.", 1 );
			return "";
		}
	}
	
	$zips_in_folder = loadDirSimple ( "$PWD/$branch/$ID/", "(\.zip|\.tar\.gz)", "f" );
	$ziplabel = (sizeof ( $zips_in_folder ) < 1) ? $ID : preg_replace ( "/(.+)\-([^\-]+)(\.zip|\.tar\.gz)/", "$2", $zips_in_folder [0] ); // grab first entry
	                                                                                                                                      
	// generalize for any relabelled build, thus 2.0.1/M200405061234/*-2.0.2.zip is possible; label = 2.0.2
	$IDlabel = $ziplabel;
	
	$opts = loadBuildConfig ( "$PWD/$branch/$ID/build.cfg" );
	
	$ret = "<li>\n";
	$ret .= "<a href=\"javascript:toggle('r$ID')\">" . "<i> " . $label . "$IDlabel</i> " . "(" . IDtoDateStamp ( $ID, 2 ) . ")" . "</a>" . "<a name=\"$ID\"></a> " . "<a href=\"?showAll=1&amp;hlbuild=$ID" . "\">" . "<img alt=\"Link to this build\" src=\"/modeling/images/link.png\"/>" . "</a>";
	
	$ret .= "<ul id=\"r$ID\"" . (($c == 0 && ! isset ( $_GET ["hlbuild"] )) || isset ( $_GET ["hlbuild"] ) && $ID == $_GET ["hlbuild"] ? "" : " style=\"display: none\"") . ">\n";
	
	$ret .= createFileLinks ($PR, $PWD, $branch, $ID, $dls, $filePre, $ziplabel );
	$ret .= getBuildArtifacts ( $PWD, "$branch/$ID" );
	$ret .= "</ul>\n";
	$ret .= "</li>\n";
	
	return $ret;
}
function loadBuildConfig($file) {
	$lines = (is_file ( $file ) && is_readable ( $file ) ? file ( $file ) : array ());
	$opts = array ();
	foreach ( $lines as $z ) {
		$regs = null;
		if (preg_match ( "/^(.+\.(?:download\.url|file|buildurl|url|name|id))=(.{2,})$/", $z, $regs )) {
			$opts [$regs [1]] = $regs [2];
		}
	}
	return $opts;
}
function getBuildArtifacts($PWD, $branchID) {
	$opts = loadBuildConfig ( "$PWD/$branchID/build.cfg");
	$ret = "";
	if (isset ( $opts ["hudson.job.url"] )) {
		$ret .= "<li>\n";
		$ret .= "<img src=\"/modeling/images/dl-more.gif\" alt=\"More info about this build\"/> Build Details\n";
		$ret .= "<ul>\n";
		$ret .= "<li>Hudson job <a href=\"" . $opts ["hudson.job.url"] . "\">" . $opts ["hudson.job.name"] . " #" . $opts ["hudson.job.id"] . "</a></li>\n";
		$ret .= "</ul>\n";
		$ret .= "</li>\n";
	}
	return $ret;
}
function showToggle($showAll, $showMax, $count) {
	$ret = "<li><a href=\"" . $_SERVER ["PHP_SELF"] . "?showAll=" . ($showAll == "1" ? "" : "1") . "&amp;showMax=$showMax\">" . ($showAll != "1" ? "show all $count" : "show only $showMax") . "...</a></li>\n";
	return $ret;
}
function showArchived($oldrels) {
	$thresh = sizeof ( $oldrels ) > 5 ? ceil ( sizeof ( $oldrels ) / 3 ) : 6;
	// print "<div id=\"midcolumn\">\n";
	print "<h4><a name=\"archives\"></a>Archived Release Builds</h4>\n";
	print "<p>Older GEF releases have been moved to archive.eclipse.org, and can be accessed here:</p>";
	print '<table cellspacing="0" cellpadding="0" border="0" style="margin:0"><tr valign="top">' . "\n";
	print "<td><ul id=\"archives\">\n";
	$cnt = - 1;
	foreach ( array_keys ( $oldrels ) as $z ) {
		$cnt ++;
		if ($cnt % $thresh == 0) {
			print "</ul></td><td><ul id=\"archives\">\n";
		}
		if (! $z || $oldrels [$z] === null) {
			$cnt --; // spacer
		}
		else {
			print "<li><a href=\"" . $oldrels [$z] [1] . "\">$z</a> (" . $oldrels [$z] [0] . ")</li>\n";
		}
	}
	print "</ul>\n";
	print "</td>";
	print "</tr></table>\n";
	// print "</div>\n";
}
?>
